<template>
    <el-dialog
      :title="!dataForm.id ? '新增' : '修改'"
      :close-on-click-modal="false"
      :visible.sync="visible">
      <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="80px">
      <el-form-item label="课程名" prop="name">
        <el-input v-model="dataForm.name" placeholder="课程名"></el-input>
      </el-form-item>
      <el-form-item label="课程简介" prop="introduction">
        <el-input v-model="dataForm.introduction" placeholder="课程简介"></el-input>
      </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="dataFormSubmit()" v-if="canSubmit">确定</el-button>
      </span>
    </el-dialog>
  </template>
  
  <script>
      import {getObj, addObj, putObj} from '@/api/teacher/course'
  
      export default {
      data () {
        return {
          visible: false,
          canSubmit: false,
          dataForm: {
            id: 0,
            name: '',
            introduction: ''
          },
          dataRule: {
            name: [
              { required: true, message: '课程名不能为空', trigger: 'blur' }
            ],
            introduction: [
              { required: true, message: '课程简介不能为空', trigger: 'blur' }
            ]
          }
        }
      },
      methods: {
        init (id) {
          this.dataForm.id = id || 0;
          this.visible = true;
          this.canSubmit = true;
          this.$nextTick(() => {
            this.$refs['dataForm'].resetFields()
            if (this.dataForm.id) {
              getObj(this.dataForm.id).then(response => {
                  this.dataForm = response.data
              })
            }
          })
        },
        // 表单提交
        dataFormSubmit () {
          this.$refs['dataForm'].validate((valid) => {
            if (valid) {
              this.canSubmit = false;
              if (this.dataForm.id) {
                  putObj(this.dataForm).then(data => {
                      this.$notify.success('修改成功')
                      this.visible = false
                      this.$emit('refreshDataList')
                  }).catch(() => {
                      this.canSubmit = true;
                  });
              } else {
                  addObj(this.dataForm).then(data => {
                      this.$notify.success('添加成功')
                      this.visible = false
                      this.$emit('refreshDataList')
                  }).catch(() => {
                      this.canSubmit = true;
                  });
              }
            }
          })
        }
      }
    }
  </script>
  